/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.activity.impl;

import org.sabayframework.activity.Activity;
import org.sabayframework.activity.ActivityContext;
import org.sabayframework.channel.Channel;

/**
 * Base class for a serialized activity that reads single element from input and writes a single
 * element into output. 
 * @author Alex Antonau
 * */
public abstract class AbstractActivity<I, O> implements Activity<I, O> {

	@Override
	public void beforeExecute(ActivityContext<I, O> ctx) throws Exception {
	}

	@Override
	/**
	 * Make sure that output is closed after execute
	 * */
	public void afterExecute(ActivityContext<I, O> ctx) throws Exception {
		ctx.getOutput().close();
	}

	@Override
	/**
	 * Return true if at least one element both in input and output queues is available. 
	 * */
	public boolean isReady(ActivityContext<I, O> ctx) throws Exception {
		if(ctx.getInput().size() == 0) return false;
		if(ctx.getOutput().freeSize() == 0) return false;
		return true;
	}

	@Override
	/**
	 * Returns true if no more elements can be read from input channel or 
	 * written into output channel.
	 * */
	public boolean isDone(ActivityContext<I, O> ctx) throws Exception {
		boolean done = false;
		final Channel<I> input = ctx.getInput();
		final Channel<O> output = ctx.getOutput();
		if(input.isClosed() && input.isEmpty()) done=true;
		if(done){
			if(input.hasFailed()) output.fail(input.getFailureCause());
		}else{
			if(output.isClosed()) done = true;
			if(done){
				if(output.hasFailed()) input.fail(output.getFailureCause());
				else {
					input.close();
				}
			}
		}
		return done;
	}

}
